﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Sql;
using System.Data.SqlClient;
using BOU_ITproject;
using System.Configuration;

namespace thailandProject.Models
{
    /// <summary>
    /// For this to work you must first run the db connection string through the AES.cs encrypter method, then
    /// store that string in the web.config file
    /// </summary>

    public class DB
    {
        public SqlConnection Conn { get; set; }

        public DB()
        {
            try
            {
                Conn = new SqlConnection();
            }
            catch (Exception ex)
            {
                ErrorLog.logError(ex);
            }
        }

        // gets encrypted conn string from web.config, encrypts it, and uses it to connect to database
        public void ConnectDB()
        {
            try
            {
                //pull database conn string out of web.config
                string s = ConfigurationManager.ConnectionStrings.ToString();

                //decrypt the string and use as conn string
                AES sec = new AES();
                string connString = sec.DecryptString(s);

                Conn = new SqlConnection(connString); //change s to connString to enable encryption

                Conn.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                ErrorLog.logError(ex);
            }
        }

        public void Connect()
        {
            try
            {
                // pull database conn string out of web.config
                string s = ConfigurationManager.ConnectionStrings.ToString();

                // open database connection
                Conn.ConnectionString = s;
                Conn.Open();
            }
            catch (Exception ex)
            {
                ErrorLog.logError(ex);
            }
        }

        // Closes the database connection
        public void Disconnect()
        {
            try
            {
                Conn.Close();
            }
            catch (Exception ex)
            {
                ErrorLog.logError(ex);
            }
        }
    }
}